package org.jeecg.modules.business.transfer.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.mapper.BasicMaterialMapper;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceipt;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceiptMaterial;
import org.jeecg.modules.business.transfer.service.IWmsMoveReceiptMaterialService;
import org.jeecg.modules.business.transfer.service.IWmsMoveReceiptService;
import org.jeecg.modules.business.transfer.vo.WmsMoveReceiptMaterialResponseVO;
import org.jeecg.modules.business.transfer.vo.WmsMoveReceiptPage;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTask;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMapper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 移库单
 * @Author: jeecg-boot
 * @Date: 2023-08-11
 * @Version: V1.0
 */
@Api(tags = "移库单")
@RestController
@RequestMapping("/business/wmsMoveReceipt")
@Slf4j
public class WmsMoveReceiptController {
    @Autowired
    private IWmsMoveReceiptService wmsMoveReceiptService;
    @Autowired
    private IWmsMoveReceiptMaterialService wmsMoveReceiptMaterialService;
    @Autowired
    private BasicMaterialMapper basicMaterialMapper;
    @Autowired
    private WmsInReceiptTaskMapper inReceiptTaskMapper;

    /**
     * 提交
     *
     * @param id
     * @param req
     * @return
     */
    @ApiOperation(value = "提交", notes = "提交")
    @PostMapping(value = "/commit")
    public Result<Void> commit(@RequestParam("id") String id,
                         HttpServletRequest req) {
        wmsMoveReceiptService.commit(id, req);
        return Result.ok();
    }

    /**
     * 分页列表查询
     *
     * @param wmsMoveReceipt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "移库单-分页列表查询", notes = "移库单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Page<WmsMoveReceipt>> queryPageList(WmsMoveReceipt wmsMoveReceipt,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        Result<Page<WmsMoveReceipt>> result = new Result<Page<WmsMoveReceipt>>();
        Page<WmsMoveReceipt> pageList = new Page<WmsMoveReceipt>(pageNo, pageSize);
        pageList = wmsMoveReceiptService.listByPage(pageList, wmsMoveReceipt);
        result.setSuccess(true);
        result.setResult(pageList);
        List<WmsMoveReceipt> records = pageList.getRecords();
        List<String> ids = records.stream().map(WmsMoveReceipt::getId).collect(Collectors.toList());
        List<WmsMoveReceiptMaterial> list = wmsMoveReceiptMaterialService.list(new LambdaQueryWrapper<WmsMoveReceiptMaterial>()
                .in(CollectionUtil.isNotEmpty(ids), WmsMoveReceiptMaterial::getWmsMoveReceiptId, ids));
        records.forEach(o -> {
            if (list.stream().filter(x -> x.getWmsMoveReceiptId().equals(o.getId())).count() > 0) {
                o.setHasChild(1);
            } else {
                o.setHasChild(0);
            }
        });
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmsMoveReceiptPage
     * @return
     */
    @AutoLog(value = "移库单-添加")
    @ApiOperation(value = "移库单-添加", notes = "移库单-添加")
    @RequiresPermissions("business:wms_move_receipt:add")
    @PostMapping(value = "/add")
    public Result add(@RequestBody WmsMoveReceiptPage wmsMoveReceiptPage) {
        WmsMoveReceipt wmsMoveReceipt = new WmsMoveReceipt();
        BeanUtils.copyProperties(wmsMoveReceiptPage, wmsMoveReceipt);
        String s = wmsMoveReceiptService.saveMain(wmsMoveReceipt, wmsMoveReceiptPage.getWmsMoveReceiptMaterialList());
        Result<String> r = new Result();
        r.setSuccess(true);
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage("添加成功！");
        r.setResult(s);
        return Result.OK(r);
    }

    /**
     * 编辑
     *
     * @param wmsMoveReceiptPage
     * @return
     */
    @AutoLog(value = "移库单-编辑")
    @ApiOperation(value = "移库单-编辑", notes = "移库单-编辑")
    @RequiresPermissions("business:wms_move_receipt:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result<String> edit(@RequestBody WmsMoveReceiptPage wmsMoveReceiptPage) {
        WmsMoveReceipt wmsMoveReceipt = new WmsMoveReceipt();
        BeanUtils.copyProperties(wmsMoveReceiptPage, wmsMoveReceipt);
        WmsMoveReceipt wmsMoveReceiptEntity = wmsMoveReceiptService.getById(wmsMoveReceipt.getId());
        if (wmsMoveReceiptEntity == null) {
            return Result.error("未找到对应数据");
        }
        wmsMoveReceiptService.updateMain(wmsMoveReceipt, wmsMoveReceiptPage.getWmsMoveReceiptMaterialList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "移库单-通过id删除")
    @ApiOperation(value = "移库单-通过id删除", notes = "移库单-通过id删除")
    @RequiresPermissions("business:wms_move_receipt:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmsMoveReceiptService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "移库单-批量删除")
    @ApiOperation(value = "移库单-批量删除", notes = "移库单-批量删除")
    @RequiresPermissions("business:wms_move_receipt:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmsMoveReceiptService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "移库单-通过id查询", notes = "移库单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmsMoveReceipt> queryById(@RequestParam(name = "id", required = true) String id) {
        WmsMoveReceipt wmsMoveReceipt = wmsMoveReceiptService.getById(id);
        if (wmsMoveReceipt == null) {
            return Result.error("未找到对应数据");
        }
        WmsInReceiptTask task = inReceiptTaskMapper.selectById(wmsMoveReceipt.getInTaskId());
        wmsMoveReceipt.setInTaskId_dictText(Optional.ofNullable(task).map(WmsInReceiptTask::getDocumentCode).orElse(""));
        return Result.OK(wmsMoveReceipt);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "移库单-物料通过主表ID查询")
    @ApiOperation(value = "移库单-物料主表ID查询", notes = "移库单-物料-通主表ID查询")
    @GetMapping(value = "/queryWmsMoveReceiptMaterialByMainId")
    public Result<List<WmsMoveReceiptMaterialResponseVO>> queryWmsMoveReceiptMaterialListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<WmsMoveReceiptMaterial> wmsMoveReceiptMaterialList = wmsMoveReceiptMaterialService.selectByMainId(id);
        List<WmsMoveReceiptMaterialResponseVO> list = BeanUtil.copyToList(wmsMoveReceiptMaterialList, WmsMoveReceiptMaterialResponseVO.class);
        List<String> materialIds = list.stream().map(WmsMoveReceiptMaterialResponseVO::getWmsBasicMaterialId).collect(Collectors.toList());
        List<BasicMaterial> basicMaterials = basicMaterialMapper.selectList(new LambdaQueryWrapper<BasicMaterial>()
                .in(CollectionUtil.isNotEmpty(materialIds), BasicMaterial::getId, materialIds));
        WmsMoveReceipt moveReceipt = wmsMoveReceiptService.getById(id);
        for (WmsMoveReceiptMaterialResponseVO vo : list) {
            if (CollectionUtil.isNotEmpty(basicMaterials)) {
                basicMaterials.forEach(o -> {
                    if (o.getId().equals(vo.getWmsBasicMaterialId())) {
                        vo.setMaterialName(o.getName());
                        vo.setMaterialCode(o.getCode());
                        vo.setSpecification(o.getSpecification());
                    }
                });
            }
            vo.setTransferFromWarehouseId(moveReceipt.getTransferFromWarehouseId());
        }
        return Result.OK(list);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmsMoveReceipt
     */
    @ApiOperation(value = "导出excel", notes = "导出excel")
    @RequiresPermissions("business:wms_move_receipt:exportXls")
    @PostMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, @RequestBody WmsMoveReceipt wmsMoveReceipt) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<WmsMoveReceipt> queryWrapper = QueryGenerator.initQueryWrapper(wmsMoveReceipt, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<WmsMoveReceipt> wmsMoveReceiptList = wmsMoveReceiptService.list(queryWrapper);
        List<String> ids = wmsMoveReceiptList.stream().map(WmsMoveReceipt::getId).collect(Collectors.toList());
        List<WmsMoveReceiptMaterial> moveReceiptMaterials = wmsMoveReceiptMaterialService.list(new LambdaQueryWrapper<WmsMoveReceiptMaterial>()
                .in(WmsMoveReceiptMaterial::getWmsMoveReceiptId, ids));
        Map<String, List<WmsMoveReceiptMaterial>> listMap = new HashMap<>();
        if (moveReceiptMaterials != null){
            listMap = moveReceiptMaterials.stream().collect(Collectors.groupingBy(WmsMoveReceiptMaterial::getWmsMoveReceiptId));
        }

        // Step.3 组装pageList
        List<WmsMoveReceiptPage> pageList = new ArrayList<WmsMoveReceiptPage>();
        for (WmsMoveReceipt main : wmsMoveReceiptList) {
            WmsMoveReceiptPage vo = new WmsMoveReceiptPage();
            BeanUtils.copyProperties(main, vo);
            List<WmsMoveReceiptMaterial> wmsMoveReceiptMaterialList = listMap.get(main.getId());
            vo.setWmsMoveReceiptMaterialList(wmsMoveReceiptMaterialList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "移库单列表");
        mv.addObject(NormalExcelConstants.CLASS, WmsMoveReceiptPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("移库单数据", "导出人:" + sysUser.getRealname(), "移库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    @RequiresPermissions("business:wms_move_receipt:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<WmsMoveReceiptPage> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsMoveReceiptPage.class, params);
                for (WmsMoveReceiptPage page : list) {
                    WmsMoveReceipt po = new WmsMoveReceipt();
                    BeanUtils.copyProperties(page, po);
                    wmsMoveReceiptService.saveMain(po, page.getWmsMoveReceiptMaterialList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
